package com.zenika.zenbinding.client.handler;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Abstract class extended by an handler bounds with a ValueModel. It implements the Observer pattern to notify the ValueModel in case of change of the value.
 * 
 * @author Zenika
 */
public abstract class ValueBindingHandler implements Handler {
  
  private List<ValueBindingListener> listenerList;
  
  public ValueBindingHandler() {
    this.listenerList = new ArrayList<ValueBindingListener>();
  }
  
  /**
   * Add a Listener to the listener list. The listener must implements the ValueBindingListener interface.
   * 
   * @param listener
   *          ValueBindingListener
   */
  public void addValueBindingListener(ValueBindingListener listener) {
    this.listenerList.add(listener);
  }
  
  /**
   * Remove a listener from the listener list.
   * 
   * @param listener
   */
  public void removeValueBindingListener(ValueBindingListener listener) {
    this.listenerList.remove(listener);
  }
  
  public abstract void setErrorStyle();
  
  public abstract void setRegularStyle();
  
  /**
   * Notify all the listeners of the value change.
   * 
   * @param value
   *          The new value
   * @param handler
   *          The handler
   */
  protected void fireChange(String value, Handler handler) {
    Iterator<ValueBindingListener> iter = this.listenerList.iterator();
    while ( iter.hasNext() ) {
      iter.next().onChange(value, handler);
    }
  }
}
